package com.uto;


import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.nutiteq.BasicMapComponent;
import com.nutiteq.android.MapView;
import com.nutiteq.components.Label;
import com.nutiteq.components.Line;
import com.nutiteq.components.LineStyle;
import com.nutiteq.components.Place;
import com.nutiteq.components.PlaceIcon;
import com.nutiteq.components.PlaceLabel;
import com.nutiteq.components.WgsPoint;
import com.nutiteq.controls.AndroidKeysHandler;
import com.nutiteq.location.LocationListener;
import com.nutiteq.location.LocationMarker;
import com.nutiteq.location.LocationSource;
import com.nutiteq.location.NutiteqLocationMarker;
import com.nutiteq.location.providers.AndroidGPSProvider;
import com.nutiteq.maps.OpenStreetMap;
import com.nutiteq.ui.ThreadDrivenPanning;
import com.nutiteq.utils.Utils;
import com.uto.backend.interfaces.IAppManager;
import com.uto.backend.interfaces.IServerResponse;
import com.uto.frontend.interfaces.IServiceListener;


public class MapViewOpenStreet extends Activity {

	private final String TAG = "com.uto.MapViewOpenStreet";

	//Server Requsets Params
	private final int RANKING_REQUEST = 5;
	private final int BUY_REQUEST = 6;
	private final int SELL_REQUEST = 7;
	private final int UPDATE_REQUEST = 8;
	private final int PROPERTY_REQUEST = 9;
	private final int DRAW_REQUEST = 10;
	private final int LOG_REQUEST = 11;

	private final int STREET_PRICE = 1000;


	private int curRequest;
	private int updateFor;
	private User curUser;



	//MapView Params
	private ZoomControls zoomControls;
	private MapView mapView; 
	private BasicMapComponent mapComponent;
	private boolean onRetainCalled;
	private Place centerPlace;
	private int[] colors={Color.MAGENTA,Color.RED,Color.BLUE,Color.YELLOW,Color.CYAN,Color.GRAY
			,Color.DKGRAY,Color.LTGRAY,Color.BLACK,Color.MAGENTA};

	//Title Params
	private int userMoney = 0;

	//Temp Params
	private PopupWindow popUp;
	private RadioGroup radioG;
	private String[] GlobOwnedStreetsArr;

	//Massage Params
	private final int IS_OK = 0;
	private final int NOT_OK = 1;


	//##################################################
	//######Map OnCreate################################
	//##################################################
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.main);
		if (customTitleSupported) {	     
			getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		}
		updateTitle();






		//		 Building title Layout.
		//		 LinearLayout titleLayout = new LinearLayout(this);
		//		 titleLayout.setOrientation(0);
		//		 LayoutParams linParams = new LayoutParams(LayoutParams.MATCH_PARENT, 35);
		//		 titleLayout.setLayoutParams(linParams);
		//		 titleLayout.setGravity(Gravity.CENTER_VERTICAL);
		//		 titleLayout.setBackgroundColor(Color.BLACK);
		//		 
		//		 ImageView utoIcon = new ImageView(this);
		//		 utoIcon.setImageResource(R.drawable.header);
		//		 utoIcon.setMaxWidth(150);
		//		 ImageView moneyIcon = new ImageView(this);
		//		 moneyIcon.setImageResource(R.drawable.coins);
		//		 moneyIcon.setMaxWidth(30);
		//		 TextView tv = new TextView(this);
		//		 int userMoney = 0;
		//			if (curUser == null) {
		//				Intent curIntent = getIntent();
		//				User tmpUser = curIntent.getParcelableExtra("user");
		//				if (tmpUser != null) {
		//					userMoney = tmpUser.getMoney();
		//				}
		//			}
		//			else {
		//				userMoney = curUser.getMoney();
		//			}
		//		 tv.setText(userMoney);
		//		titleLayout.addView(utoIcon);
		//		titleLayout.addView(moneyIcon);
		//		titleLayout.addView(tv);
		//
		//		 
		//		 


		onRetainCalled = false;

		//The Coordinates of center location.
		LocationManager locationManager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location lastLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		double centerLng;
		double centerLat;

		if (lastLoc == null){	
			centerLng = 35.214497; 
			centerLat = 31.782256;
		}
		else
		{
			centerLng = lastLoc.getLongitude();
			centerLat = lastLoc.getLatitude();
		}

		//Simple Map
		mapComponent = new BasicMapComponent("tutorial", "Nutiteq", "Android Mapper", 
				1, 1, new WgsPoint(centerLng, centerLat), 17); 
		//Open Street Map.
		mapComponent.setMap(OpenStreetMap.MAPNIK); 

		//Adds Icon to the center location.
		centerPlace = new Place(0,"You Are Here...", Utils.createImage("/res/drawable/palyer.png"), centerLng,centerLat);
		mapComponent.addPlace(centerPlace);

		//The Style of the border lines.
		//		LineStyle BorderStyle = new LineStyle( -10555551,8);
		LineStyle BorderStyle = new LineStyle( Color.MAGENTA,8);
		WgsPoint[] linePointsUp={
				new WgsPoint(35.20832,31.78592),
				new WgsPoint(35.22383,31.78517),
		};
		Line LineUp = new Line(linePointsUp);
		LineUp.setStyle(BorderStyle);
		WgsPoint[] linePointsLeft={
				new WgsPoint(35.20832,31.78592),
				new WgsPoint(35.20941,31.77634),
		};
		Line LineLeft = new Line(linePointsLeft);
		LineLeft.setStyle(BorderStyle);
		WgsPoint[] linePointsDown={
				new WgsPoint(35.22036,31.77691),
				new WgsPoint(35.20941,31.77634),
		};

		Line LineDown = new Line(linePointsDown);
		LineDown.setStyle(BorderStyle);
		WgsPoint[] linePointsRight={
				new WgsPoint(35.22036,31.77691),
				new WgsPoint(35.22383,31.78517),
		};

		Line LineRight = new Line(linePointsRight);
		LineRight.setStyle(BorderStyle);



		WgsPoint[] linePoints={
				new WgsPoint(35.21677,31.78099),
				new WgsPoint(35.21744,31.78106),
				new WgsPoint(35.21838,31.78114),
				new WgsPoint(35.21905,31.78116),
				new WgsPoint(35.21954,31.78121)};
		Line line = new Line(linePoints);
		LineStyle p1Style = new LineStyle( -16556961,5);
		line.setStyle(p1Style);
		//		mapComponent.addLine(line);
		//		mapComponent.addPolygon(borderPolygon);
		mapComponent.addLine(LineDown);
		mapComponent.addLine(LineUp);
		mapComponent.addLine(LineLeft);
		mapComponent.addLine(LineRight);


		mapComponent.setPanningStrategy(new ThreadDrivenPanning()); 
		mapComponent.setControlKeysHandler(new AndroidKeysHandler()); 
		mapComponent.startMapping();
		mapView = new MapView(this, mapComponent);

		//Setting the zoom
		zoomControls = new ZoomControls(this); 

		zoomControls.setOnZoomInClickListener(new View.OnClickListener() { 
			public void onClick(final View v) { 
				mapComponent.zoomIn(); } }); 

		zoomControls.setOnZoomOutClickListener(new View.OnClickListener() { 
			public void onClick(final View v) {
				mapComponent.zoomOut(); } });

		final LocationSource locationSource = new AndroidGPSProvider(
				(LocationManager) getSystemService(Context.LOCATION_SERVICE), 1000L);
		final LocationMarker marker = 
			new NutiteqLocationMarker(new PlaceIcon(Utils.createImage("/res/drawable/palyer.png")), 3000, true);
		locationSource.setLocationMarker(marker);

		//this listener is only for removing the initial marker we put for the center point
		locationSource.addLocationListener(new LocationListener(){
			public void setLocation(WgsPoint arg0) {
				if (centerPlace!=null){
					mapComponent.removePlace(centerPlace);
					centerPlace = null;
				}
			}
		});

		mapComponent.setLocationSource(locationSource);
		Label lable1 = new PlaceLabel("lable tmp");
		//		place


		final RelativeLayout relativeLayout = new RelativeLayout(this); 
		setContentView(relativeLayout);

		final RelativeLayout.LayoutParams mapViewLayoutParams = new RelativeLayout.LayoutParams( 
				RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT); 
		relativeLayout.addView(mapView, mapViewLayoutParams);


		//Add Zoom controls View to the RelativeLayout 
		final RelativeLayout.LayoutParams zoomControlsLayoutParams = new 
		RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
		zoomControlsLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); 
		zoomControlsLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); 
		relativeLayout.addView(zoomControls, zoomControlsLayoutParams);
		callDraw();


	}

	@Override 
	public Object onRetainNonConfigurationInstance() { 
		onRetainCalled = true; 
		return mapComponent; 
	}

	protected void onDestroy() { 
		Log.d(TAG,"in the on destroy");
		super.onDestroy();
		callDestroyService();
		finish();
	}
	private void updateTitle() {

		TextView myTitleText = (TextView) findViewById(R.id.titleMoney);
		if ( myTitleText != null ) {
			if (curUser == null) {
				Intent curIntent = getIntent();
				User tmpUser = curIntent.getParcelableExtra("user");
				if (tmpUser != null) {
					userMoney = tmpUser.getMoney();
				}
			}
			else {
				userMoney = curUser.getMoney();
			}
			myTitleText.setText("  "+userMoney);
		}

	}
	private WgsPoint[] convertToWgs(double[] streetLine) {
		WgsPoint curPoint;
		WgsPoint[] streetWgs = new WgsPoint[streetLine.length/2];
		int arrIndex =0;
		for (int i = 0; i < streetLine.length; i++) {
			curPoint = new WgsPoint(streetLine[i], streetLine[++i]);
			streetWgs[arrIndex++] = curPoint;
		}
		return streetWgs;		
	}


	private void drawLine(WgsPoint[] linePoints, int color) {
		Line line = new Line(linePoints);
		LineStyle style = new LineStyle( colors[color],5);
		line.setStyle(style);
		mapComponent.addLine(line);
	}

	private double[] lineToArr(String line) {
		line =line.replaceAll(" ",",");
		Log.d(TAG,"line after split: "+line);
		String[] strArr = line.split(",");
		for (int i = 0; i < strArr.length; i++) {
			Log.d(TAG,strArr[i]);
		}
		Log.d(TAG,strArr.toString());
		double[] coorArr = new double[strArr.length];
		for (int i = 0; i < strArr.length; i++) {
			coorArr[i]= Double.parseDouble(strArr[i]);	
		}
		return coorArr;
	}


	private void drawMap(Map<String, Object> data) {
		mapComponent.removeAllPlaces();
		mapComponent.addPlace(centerPlace);
		//		mapComponent.setLocationSource(locationSource);
		int colorType;
		String lineArr;
		double[] coorArr;
		for (int f=0; f<data.size()/2; f++) {
			colorType = Integer.parseInt((String)data.get("color"+f));
			Log.d(TAG,"got color: "+colorType);
			lineArr = (String)data.get("line"+f);
			Log.d(TAG,"got line: "+lineArr);
			coorArr = lineToArr(lineArr);
			drawLine(convertToWgs(coorArr), colorType);
			Log.d(TAG,"got line: "+lineArr);
			Log.d(TAG,"parsed to : "+coorArr.toString());
		} 		
	}

	//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	// menu item constants
	//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	public static final int Menu1 = Menu.FIRST + 1;
	public static final int Menu2 = Menu.FIRST + 2;
	public static final int Menu3 = Menu.FIRST + 3;
	public static final int Menu4 = Menu.FIRST + 4;
	public static final int Menu5 = Menu.FIRST + 5;
	public static final int Menu6 = Menu.FIRST + 6;

	/** create the menu items */
	public void populateMenu(Menu menu) {

		// enable keyb shortcuts, qwerty mode = true means only show keyb shortcuts (not numeric) and vice versa
		// these only show up in context menu, not options menu
		menu.setQwertyMode(true);

		MenuItem item1 = menu.add(0, Menu1, 0, "Buy This Street!");
		{
			item1.setAlphabeticShortcut('a');
			item1.setIcon( R.drawable.monopoly_house);
		}

		MenuItem item2 = menu.add(0, Menu2, 0, "Sell Properties");
		{
			item2.setAlphabeticShortcut('b');
			item2.setIcon( R.drawable.monopoly_hotel);
		}

		MenuItem item3 = menu.add(0, Menu3, 0, "My Fortune");
		{
			item3.setNumericShortcut('1');
			item3.setIcon( R.drawable.treasurechest);
		}

		MenuItem item4 = menu.add(0, Menu4,0, "Ranking");
		{
			item4.setNumericShortcut('2');
			item4.setIcon( R.drawable.trophy_gold_38);
		}
		MenuItem item5 = menu.add(0, Menu5,0, "LastActions");
		{
			item5.setNumericShortcut('3');
			item5.setIcon( R.drawable.info);
		}
		MenuItem item6 = menu.add(0, Menu6,0, "Exit");
		{
			item6.setNumericShortcut('4');
			item6.setIcon( R.drawable.exit);
		}

	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		populateMenu(menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.about:
			new AlertDialog.Builder(this)
			.setTitle(getString(R.string.about_title))
			.setMessage(getString(R.string.about_body))
			.show();
			return true;

		case R.id.my_property:
			Dialog d = new ActionDilalog(this , getString(R.string.my_property));
			d.show();
			return true;
		case Menu1:
			updateFor = BUY_REQUEST;
			callUpdateData();
			Log.d("MenuDebug", "select menu BUY");
			return true;
		case Menu2:
			updateFor=SELL_REQUEST;
			callUpdateData();
			Log.d("MenuDebug", "select menu Sell");
			return true;
		case Menu3:
			updateFor=PROPERTY_REQUEST;
			callUpdateData();
			Log.d("MenuDebug", "select menu My fortune");
			return true;
		case Menu4:
			callServerRanking();
			Log.d("MenuDebug", "select menu Ranking");
			return true;
		case Menu5:
			callLog();
			Log.d("MenuDebug", "select menu Log");
			return true;
		case Menu6:
			Log.d("MenuDebug", "select menu Exit");
			exitPopUp();
			return true;
		default: 
			Log.d("MenuDebug", "select menu streets");
			return true;
		}
	}


	/**
	 * overriding back button
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			Log.d(this.getClass().getName(), "back button pressed");
			Toast.makeText(this, "To Close UTO Select Menu and Exit", Toast.LENGTH_SHORT).show();
		}
		return false;
	}

	//##################################################
	//######PopUp's Methods Methods#####################
	//##################################################

	public void exitPopUp() { 
		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		popUp = new PopupWindow(this);
		TableLayout layout = new TableLayout (this);
		layout.setLayoutParams( new TableLayout.LayoutParams(10,5) );
		layout.setPadding(1,1,1,1);
		layout.setOrientation(LinearLayout.VERTICAL);

		TableRow trFirst = new TableRow(this);
		ImageView ivFirst= new ImageView(this);
		ivFirst.setImageResource(R.drawable.x);
		TextView tvFirst= new TextView(this);
		tvFirst.setTextSize(20);
		tvFirst.setText("        Exit UTO ");
		trFirst.addView(ivFirst);
		trFirst.addView(tvFirst);
		layout.addView(trFirst);
		TableLayout tableLayout1 = new TableLayout(this);

		TableRow tr2 = new TableRow(this);
		Button butExit = new Button(this);
		butExit.setText("Exit UTO");
		butExit.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				popUp.dismiss();
				onDestroy();
			}
		});
		butExit.setTextColor(Color.RED);
		tr2.addView(butExit);

		Button butQuit = new Button(this);
		butQuit.setText("Quit Game");
		butQuit.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				popUp.dismiss();
				SharedPreferences settings = getSharedPreferences(UTO.USER_FILE, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("firstName", null);
				editor.putString("lastName", null);
				editor.putString("username", null);
				editor.putString("password", null);
				editor.putBoolean("inGame", false);
				// Commit the edits!
				editor.commit();
				//			    Intent intent = new Intent(MapViewOpenStreet.this , UTO.class);
				//			    finish();
				//				startActivity(intent);
			}
		});
		tr2.addView(butQuit);
		tableLayout1.addView(tr2);


		Button but = new Button(this);
		but.setText("Cancel");
		but.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				popUp.dismiss();
			}
		});
		but.setWidth(165);
		layout.addView(tableLayout1);

		TableLayout tableLayout2 = new TableLayout(this);
		TableRow trCancel = new TableRow(this);
		trCancel.addView(but);
		tableLayout2.addView(trCancel);
		layout.addView(tableLayout2);
		//		layout.addView(but, params);
		popUp.setContentView(layout);
		popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
		popUp.update(5, 50, 250, 220);
	}



	public void buyPopUp(String user) { 
		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		popUp = new PopupWindow(this);
		TableLayout layout = new TableLayout (this);
		layout.setLayoutParams( new TableLayout.LayoutParams(4,5) );
		layout.setPadding(1,1,1,1);
		layout.setOrientation(LinearLayout.VERTICAL);
		TableRow trFirst = new TableRow(this);
		ImageView ivFirst= new ImageView(this);
		ivFirst.setImageResource(R.drawable.monopoly_house_big);
		TextView tvFirst= new TextView(this);

		tvFirst.setText("Buy Action Window");
		//		trFirst.addView(ivFirst);
		//		trFirst.addView(tvFirst);
		layout.addView(trFirst);
		Log.d(TAG,"parsing the given buy server string");

		int buyStatus= -1;
		if (user.equals(curUser.getUsername())) {
			Log.d(TAG,"equals the user name: "+curUser.getUsername());
			buyStatus=0;
		}
		else if (user.equals("sold")) {
			Log.d(TAG,"street sold to me");
			buyStatus=1;
		}
		else {
			Log.d(TAG,"other user owned this street.");
			buyStatus=2;
		}
		TableRow tr = new TableRow(this);
		ImageView iv= new ImageView(this);
		TextView tv= new TextView(this);


		switch (buyStatus) {
		case 0:
			iv.setImageResource(R.drawable.cancel);
			tv.setText("You Allready Owned this street");
			break;
		case 1:
			iv.setImageResource(R.drawable.ok);
			tv.setText("You Now Own This Street");
			break;
		case 2:
			iv.setImageResource(R.drawable.cancel);
			tv.setText("This Street belongs to : "+user);
			break;			
		default:
			break;
		}
		tr.addView(iv);
		tr.addView(tv);
		layout.addView(tr);
		Button but = new Button(this);
		but.setText("OK!");
		but.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				popUp.dismiss();
			}
		});
		layout.addView(but, params);
		popUp.setContentView(layout);
		popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
		popUp.update(5, 50, 250, 120);
	}



	public void sellPropPopUp() {


		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
		popUp = new PopupWindow(this);
		TableLayout layout = new TableLayout (this);
		ScrollView scroll= new  ScrollView(this);
		layout.setLayoutParams( new TableLayout.LayoutParams(4,5) );
		layout.setPadding(1,1,1,1);
		layout.setOrientation(LinearLayout.VERTICAL);
		TableRow trFirst = new TableRow(this);
		ImageView ivFirst= new ImageView(this);
		ivFirst.setImageResource(R.drawable.coins);
		TextView tvFirst= new TextView(this);

		tvFirst.setText("Your Balance: "+curUser.getMoney());
		trFirst.addView(ivFirst);
		trFirst.addView(tvFirst);
		layout.addView(trFirst);
		radioG = new RadioGroup(this);
		for (int f=0; f<GlobOwnedStreetsArr.length; f++) {
			RadioButton rb = new RadioButton(this);
			rb.setText(GlobOwnedStreetsArr[f]);
			rb.setId(f);
			if (f==0) 
				rb.setChecked(true);
			rb.setTypeface(Typeface.SANS_SERIF);
			radioG.addView(rb);

		} // for
		//		//debug
		//		for (int i=0; i<26; i++) {
		//			RadioButton rb = new RadioButton(this);
		//			rb.setText("aaa");
		//			rb.setId(50+i);
		//			rb.setTypeface(Typeface.SANS_SERIF);
		//			radioG.addView(rb);
		//		}
		//		TableLayout tableL = new TableLayout(this);
		//		tableL.addView(radioG);
		////		scroll.addView(radioG);

		TableRow trbut1 = new TableRow(this);


		Button but = new Button(this);
		but.setText("Sell");
		but.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				int curId = radioG.getCheckedRadioButtonId();
				Log.d(TAG, "click on sell"+curId+" "+GlobOwnedStreetsArr[curId]);
				popUp.dismiss();
				callSellStreet(curId);
			}
		});
		trbut1.addView(but);
		Button but1 = new Button(this);
		but1.setText("Cancel");
		but1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				popUp.dismiss();
			}
		});
		trbut1.addView(but1);
		TableLayout tableL = new TableLayout(this);
		tableL.addView(radioG);
		tableL.addView(trbut1);
		scroll.addView(tableL);
		layout.addView(scroll);
		popUp.setContentView(layout);
		popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
		popUp.update(5, 50, 210, 300);
	}


	public void myProp() { 
		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		popUp = new PopupWindow(this);
		TableLayout layout = new TableLayout (this);
		layout.setLayoutParams( new TableLayout.LayoutParams(4,5) );
		layout.setPadding(1,1,1,1);
		layout.setOrientation(LinearLayout.VERTICAL);
		TableRow trFirst = new TableRow(this);
		ImageView ivFirst= new ImageView(this);
		ivFirst.setImageResource(R.drawable.coins);
		TextView tvFirst= new TextView(this);

		tvFirst.setText("Your Balance: "+curUser.getMoney());
		trFirst.addView(ivFirst);
		trFirst.addView(tvFirst);
		layout.addView(trFirst);
		for (int f=0; f<GlobOwnedStreetsArr.length; f++) {
			TableRow tr = new TableRow(this);
			ImageView iv= new ImageView(this);
			iv.setImageResource(R.drawable.monopoly_house);
			TextView tv= new TextView(this);
			tv.setText(GlobOwnedStreetsArr[f]);
			tr.addView(iv);
			tr.addView(tv);
			layout.addView(tr);
		} // for
		Button but = new Button(this);
		but.setText("OK!");
		but.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				popUp.dismiss();
			}
		});
		layout.addView(but, params);
		popUp.setContentView(layout);
		popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
		popUp.update(5, 50, 210, 250);




	}


	public void logPopUp(Map<String,Object> data) {

		int[] playersPics ={R.drawable.monopoly_hotel_28,
				R.drawable.monopoly_house_28,
				R.drawable.fst,
				R.drawable.coins
		};
		int[] textColors = {Color.WHITE,Color.WHITE,Color.RED,Color.GREEN};

		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		popUp = new PopupWindow(this);
		TableLayout layout = new TableLayout (this);
		layout.setLayoutParams( new TableLayout.LayoutParams(4,5) );
		layout.setPadding(1,1,1,1);
		layout.setOrientation(LinearLayout.VERTICAL);

		TableRow trFirst = new TableRow(this);
		TextView tvFirst= new TextView(this);
		tvFirst.setText("Recent Events");
		tvFirst.setTextSize(25);
		ImageView ivFirst = new ImageView(this);
		ivFirst.setImageResource(R.drawable.info);
		trFirst.addView(ivFirst);
		trFirst.addView(tvFirst);
		layout.addView(trFirst);

		String msg;
		int msgType;
		ScrollView scroll= new  ScrollView(this);
		TableLayout tableL = new TableLayout(this);
		for (int f=0; f<data.size()/2; f++) {
			msgType = (Integer)data.get("msgType"+f);
			msg = (String)data.get("msg"+f);
			TableRow tr = new TableRow(this);
			ImageView iv= new ImageView(this);
			iv.setImageResource(playersPics[msgType]);
			TextView tv= new TextView(this);
			tv.setTextColor(textColors[msgType]);
			tv.setText(" "+msg);
			tv.setTextSize(10);
			tr.addView(iv);
			tr.addView(tv);
			tableL.addView(tr);

			//			//TODO: 
			//			//DEBUG 
			//			TextView tv1= new TextView(this);
			//			tv.setTextColor(textColors[msgType]);
			//			TableRow tr1 = new TableRow(this);
			//			tr1.addView(tv1);
			//			tableL.addView(tr1);
			//			//END DEBUG

			Log.d(TAG, "message"+f);
		} 
		Button but = new Button(this);
		but.setText("OK!");
		but.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Log.d(TAG,"in the OK but");
				popUp.dismiss();
			}
		});
		tableL.addView(but,params);
		//		tableL.addView(but);
		scroll.addView(tableL);
		layout.addView(scroll);
		popUp.setContentView(layout);
		popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
		popUp.update(5, 50, 250, 420);
	}

	public void rankingLayout(Map<String,Object> data) {

		int[] playersPics ={R.drawable.kingicon,
				R.drawable.player1_28,
				R.drawable.player2_28,
				R.drawable.player3_28,
				R.drawable.player4_28};

		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		popUp = new PopupWindow(this);
		TableLayout layout = new TableLayout (this);
		layout.setLayoutParams( new TableLayout.LayoutParams(4,5) );
		layout.setPadding(1,1,1,1);
		layout.setOrientation(LinearLayout.VERTICAL);


		TableRow trFirst = new TableRow(this);
		TextView tvFirst= new TextView(this);
		tvFirst.setText("Game Ranking");
		tvFirst.setTextSize(25);
		ImageView ivFirst = new ImageView(this);
		ivFirst.setImageResource(R.drawable.podium1);
		trFirst.addView(ivFirst);
		trFirst.addView(tvFirst);
		layout.addView(trFirst);


		for (int f=0; f<data.size(); f++) {
			TableRow tr = new TableRow(this);
			ImageView iv= new ImageView(this);
			iv.setImageResource(playersPics[f]);
			TextView tv= new TextView(this);
			tv.setText("   "+data.get("user"+f));
			tv.setTextSize(20);
			tr.addView(iv);
			tr.addView(tv);
			layout.addView(tr);
			layout.addView(new TableRow(this));
			layout.addView(new TableRow(this));
		} 
		Button but = new Button(this);
		but.setText("OK!");
		but.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				popUp.dismiss();
			}
		});
		layout.addView(but, params);
		popUp.setContentView(layout);
		popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
		popUp.update(5, 50, 250, 300);
	}



	//##################################################
	//######Calling to the Manager Methods##############
	//##################################################
	private void callDestroyService() {
		IAppManager manager = MyServiceConnection.getAppManager();
		if (manager==null){
			Log.v(TAG, "IAppManager is null");
			Toast.makeText(MapViewOpenStreet.this, "Request Failed Try Again Later1", Toast.LENGTH_LONG).show();
			return;
		}
		try {
			manager.destroyService();
		} catch (RemoteException e) {
			e.printStackTrace();
			Toast.makeText(MapViewOpenStreet.this, "Request to app manager failed", Toast.LENGTH_LONG).show();
			return;
		}
	}


	private void callServerRanking() {
		IAppManager manager = MyServiceConnection.getAppManager();
		if (manager==null){
			Log.v(TAG, "IAppManager is null");
			Toast.makeText(MapViewOpenStreet.this, "Request Failed Try Again Later1", Toast.LENGTH_LONG).show();
			return;
		}
		try {
			curRequest=RANKING_REQUEST;
			String userName = "";
			if (curUser == null) {
				Intent curIntent = getIntent();
				User tmpUser = curIntent.getParcelableExtra("user");
				if (tmpUser != null) {
					userName = tmpUser.getUsername();
				}
			}
			else {
				userName = curUser.getUsername();
			}
			manager.gameRanking(userName,listener);
		} catch (RemoteException e) {
			e.printStackTrace();
			Toast.makeText(MapViewOpenStreet.this, "Request to app manager failed", Toast.LENGTH_LONG).show();
			return;
		}
	}


	private void callUpdateData() {
		IAppManager manager = MyServiceConnection.getAppManager();
		if (manager==null){
			Log.v(TAG, "IAppManager is null");
			Toast.makeText(MapViewOpenStreet.this, "Request Failed Try Again Later1", Toast.LENGTH_LONG).show();
			return;
		}
		try {
			curRequest=UPDATE_REQUEST;
			String userName = "";
			if (curUser == null) {
				Intent curIntent = getIntent();
				User tmpUser = curIntent.getParcelableExtra("user");
				if (tmpUser != null) {
					userName = tmpUser.getUsername();
				}
			}
			else {
				userName = curUser.getUsername();
			}
			manager.updateGameData(userName,listener);
		} catch (RemoteException e) {
			e.printStackTrace();
			Toast.makeText(MapViewOpenStreet.this, "Request to app manager failed", Toast.LENGTH_LONG).show();
			return;
		}
	}


	private void callSellStreet(int street) {
		IAppManager manager = MyServiceConnection.getAppManager();
		if (manager==null){
			Log.v(TAG, "IAppManager is null");
			Toast.makeText(MapViewOpenStreet.this, "Request Failed Try Again Later1", Toast.LENGTH_LONG).show();
			return;
		}
		try {
			curRequest=SELL_REQUEST;
			String userName = "";
			if (curUser == null) {
				Intent curIntent = getIntent();
				User tmpUser = curIntent.getParcelableExtra("user");
				if (tmpUser != null) {
					userName = tmpUser.getUsername();
				}
			}
			else {
				userName = curUser.getUsername();
			}
			manager.sellStreet(userName, street, listener);
		} catch (RemoteException e) {
			e.printStackTrace();
			Toast.makeText(MapViewOpenStreet.this, "Request to app manager failed", Toast.LENGTH_LONG).show();
			return;
		}
	}

	private void callDraw() {
		IAppManager manager = MyServiceConnection.getAppManager();
		if (manager==null){
			Log.v(TAG, "IAppManager is null");
			Toast.makeText(MapViewOpenStreet.this, "Request Failed Try Again Later1", Toast.LENGTH_LONG).show();
			return;
		}
		try {
			curRequest=DRAW_REQUEST;
			String userName = "";
			if (curUser == null) {
				Intent curIntent = getIntent();
				User tmpUser = curIntent.getParcelableExtra("user");
				if (tmpUser != null) {
					userName = tmpUser.getUsername();
				}
			}
			else {
				userName = curUser.getUsername();
			}
			manager.drawMap(userName, listener);
		} catch (RemoteException e) {
			e.printStackTrace();
			Toast.makeText(MapViewOpenStreet.this, "Request to app manager failed", Toast.LENGTH_LONG).show();
			return;
		}
	}


	private void callLog() {
		IAppManager manager = MyServiceConnection.getAppManager();
		if (manager==null){
			Log.v(TAG, "IAppManager is null");
			Toast.makeText(MapViewOpenStreet.this, "Request Failed Try Again Later1", Toast.LENGTH_LONG).show();
			return;
		}
		try {
			curRequest=LOG_REQUEST;
			String userName = "";
			if (curUser == null) {
				Intent curIntent = getIntent();
				User tmpUser = curIntent.getParcelableExtra("user");
				if (tmpUser != null) {
					userName = tmpUser.getUsername();
				}
			}
			else {
				userName = curUser.getUsername();
			}
			manager.log(userName, listener);
		} catch (RemoteException e) {
			e.printStackTrace();
			Toast.makeText(MapViewOpenStreet.this, "Request to app manager failed", Toast.LENGTH_LONG).show();
			return;
		}
	}


	private void callBuyStreet() {
		IAppManager manager = MyServiceConnection.getAppManager();
		if (manager==null){
			Log.v(TAG, "IAppManager is null");
			Toast.makeText(MapViewOpenStreet.this, "Request Failed Try Again Later1", Toast.LENGTH_LONG).show();
			return;
		}
		try {
			curRequest=BUY_REQUEST;
			String userName = "";
			int curMoney =0;
			if (curUser == null) {
				Intent curIntent = getIntent();
				User tmpUser = curIntent.getParcelableExtra("user");
				if (tmpUser != null) {
					userName = tmpUser.getUsername();
					curMoney = tmpUser.getMoney();
				}
			}
			else {
				userName = curUser.getUsername();
				curMoney = curUser.getMoney();
			}

			//Checking if we have enough money.
			if (curMoney<STREET_PRICE) {
				Toast.makeText(MapViewOpenStreet.this, "You Don't have enough money!\n You need 1000$ to buy street.", Toast.LENGTH_LONG).show();
				return;
			}
			//Getting the coordinates.
			//The Coordinates of center location.
			LocationManager locationManager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
			Location lastLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			double centerLng;
			double centerLat;
			if (lastLoc == null){
				centerLng = 35.21677; 
				centerLat = 31.78099;
				Log.e(TAG,"Error with coordinates.");
			}
			else
			{
				centerLng = lastLoc.getLongitude();
				centerLat = lastLoc.getLatitude();
			}
			manager.buy(userName,centerLat,centerLng, listener);
		} catch (RemoteException e) {
			e.printStackTrace();
			Toast.makeText(MapViewOpenStreet.this, "Request to app manager failed", Toast.LENGTH_LONG).show();
			return;
		}
	}


	//##################################################
	//######Respones Handlers###########################
	//##################################################
	private final IServiceListener.Stub listener = new IServiceListener.Stub(){

		public void handleMessage(IServerResponse response) {
			Log.d(TAG,"In the handle msg");
			Log.d(TAG,"cur request is: "+curRequest);
			switch (curRequest) {
			case RANKING_REQUEST:
				if (handleBadMsg(response)!=true) { //msg is ok
					Message msg = new Message();
					msg.arg1 = RANKING_REQUEST;
					try {
						msg.obj = response.getData();
					} catch (RemoteException e) {
						Log.e(TAG, "handleMSG get data failed");
						e.printStackTrace();
					}
					handler.sendMessage(msg);	
				}
				break;
			case BUY_REQUEST:
				Log.d(TAG,"In the handle msg buy request");
				if (handleBadMsg(response)!=true) { //msg is ok
					Message msg = new Message();
					msg.arg1 = BUY_REQUEST;
					try {
						msg.obj = response.getData();
					} catch (RemoteException e) {
						Log.e(TAG, "handleMSG get data failed");
						e.printStackTrace();
					}
					handler.sendMessage(msg);	
				}
				break;

			case SELL_REQUEST:
				Log.d(TAG,"In the handle msg sell request");
				if (handleBadMsg(response)!=true) { //msg is ok
					Message msg = new Message();
					msg.arg1 = SELL_REQUEST;
					handler.sendMessage(msg);	
				}
				break;	
			case UPDATE_REQUEST:
				Log.d(TAG,"In the handle msg update request");
				if (handleBadMsg(response)!=true) { //msg is ok
					Message msg = new Message();
					msg.arg1 = UPDATE_REQUEST;
					try {
						msg.obj = response.getData();
					} catch (RemoteException e) {
						Log.e(TAG, "handleMSG get data failed");
						e.printStackTrace();
					}
					handler.sendMessage(msg);	
				}
				break;
			case DRAW_REQUEST:
				Log.d(TAG,"In the handle msg draw request");
				if (handleBadMsg(response)!=true) { //msg is ok
					Message msg = new Message();
					msg.arg1 = DRAW_REQUEST;
					try {
						msg.obj = response.getData();
					} catch (RemoteException e) {
						Log.e(TAG, "handle MSG get data failed");
						e.printStackTrace();
					}
					handler.sendMessage(msg);	
				}
				break;
			case LOG_REQUEST:
				//				Toast.makeText(MapViewOpenStreet.this, "Log Request", Toast.LENGTH_LONG).show();
				Log.d(TAG,"In the handle msg log request");
				if (handleBadMsg(response)!=true) { //msg is ok
					Message msg = new Message();
					msg.arg1 = LOG_REQUEST;
					try {
						msg.obj = response.getData();
					} catch (RemoteException e) {
						Log.e(TAG, "handleMSG get data failed");
						e.printStackTrace();
					}
					handler.sendMessage(msg);	
				}
				break;
			default:
				break;
			}
		}
	};

	private boolean handleBadMsg(IServerResponse response) {
		Message msg = new Message();
		try {
			if (response == null)
			{
				msg.arg1 = NOT_OK;
				handler.sendMessage(msg);
				Log.e(TAG, "null response");
				return true;
			}
			else if (!response.isOk())
			{
				msg.arg1 = NOT_OK;
				msg.obj = response.getMessage();
				handler.sendMessage(msg);
				return true;
			}
		} catch (Exception e) {
			msg.arg1 = NOT_OK;
			handler.sendMessage(msg);
			e.printStackTrace();
			return true;
		}
		return false;
	}


	private Handler handler = new Handler(){
		public void handleMessage(Message msg){
			Log.d(TAG,"In the handler handle msg");
			Map<String,Object> data;
			switch (msg.arg1) {
			case NOT_OK:
				String message = (String)msg.obj;
				if (message != null)
					Toast.makeText(MapViewOpenStreet.this, message, Toast.LENGTH_LONG).show();
				else
					Toast.makeText(MapViewOpenStreet.this, "Request Failed", Toast.LENGTH_LONG).show();
				break;
			case RANKING_REQUEST:
				data = (Map<String,Object>)msg.obj;
				if (data!=null)
					rankingLayout(data);
				else
					Log.e(TAG, "handleMSG nranking null data.");
				break;

			case UPDATE_REQUEST:
				Log.d(TAG,"In the handler handle msg UPDATE REQUEST");
				data = (Map<String,Object>)msg.obj;
				if (data!=null) {
					curUser = (User)data.get("curUser");
					updateTitle();
					try {
						//JSONObject streetObj = new JSONObject(curUser.getStreets());
						String str = curUser.getStreets();
						Log.d(TAG+" the str log",str);
						if (str.equalsIgnoreCase("[]")) 
							GlobOwnedStreetsArr = new String[0];
						else{
							//						str.replace('"', '/');
							str=str.substring(1,str.length()-1);
							Log.d(TAG,"the street string is: "+str);
							String[] streets=str.split(",");
							for (int i = 0; i < streets.length; i++) {
								streets[i]= streets[i].substring(1, streets[i].length()-1);
								Log.d(TAG,streets[i]);
							}
							GlobOwnedStreetsArr = streets;
						}
						switch (updateFor) {
						case SELL_REQUEST:
							sellPropPopUp();
							break;
						case PROPERTY_REQUEST:
							myProp();
							callDraw();
							break;
						case BUY_REQUEST:
							callBuyStreet();
							break;
						default:
							break;
						}


					} catch (Exception e) {
						Log.e(TAG, "Error parsing sreets." +e.toString());
						e.printStackTrace();
					}
				}
				else
					Log.e(TAG, "handleMSG nranking null data.");
				break;
			case BUY_REQUEST:
				data = (Map<String,Object>)msg.obj;
				if (data!=null)
					buyPopUp((String)data.get("buyMsg"));
				else
					Log.e(TAG, "handleMSG BUY null data.");
				callDraw();
				break;
			case SELL_REQUEST:
				Toast.makeText(MapViewOpenStreet.this, "Street Sold", Toast.LENGTH_LONG).show();
				callDraw();
				break;
			case DRAW_REQUEST:
				data = (Map<String,Object>)msg.obj;
				if (data!=null)
					drawMap(data);
				else
					Log.e(TAG, "handleMSG nranking null data.");
				break;
				//				Toast.makeText(MapViewOpenStreet.this, "Draw Map", Toast.LENGTH_LONG).show();
			case LOG_REQUEST:
				data = (Map<String,Object>)msg.obj;
				if (data!=null)
					logPopUp(data);
				else
					Log.e(TAG, "handleMSG nranking null data.");
				break;
			default:
				break;
			}
		}


	};
}


